<template>
  <a-modal
    :visible="visible"
    :footer="null"
    centered
    :width="500"
    :keyboard="false"
    :maskClosable="false"
    @cancel="onClose"
    :bodyStyle="{
      overFlow: 'hidden',
      padding: 0,
    }"
    title="绑定手机号"
  >
    <div class="modal-content">
      <div>
        <div class="flex align-center phone-input-wrap">
          <div style="padding-right: 10px">中国 +86</div>
          <a-input
            placeholder="请输入您的手机号码"
            size="large"
            v-model:value="phoneNumber"
            :max-length="11"
            autofocus
            ref="phoneInputRef"
            class="phone-input"
          />
        </div>

        <div class="flex align-center code-input-wrap">
          <a-input
            placeholder="请输入短信验证码"
            size="large"
            v-model:value="verifyCode"
            :max-length="4"
            class="code-input"
          />
          <a-button
            type="link"
            :disabled="!phoneChecked || timeCounting"
            @click="getCode()"
            style="font-size: 16px; padding: 0; margin: 0"
            >{{ timeCounting ? `重新获取${timeCount} 秒` : `获取验证码` }}
          </a-button>
        </div>
        <a-button
          type="primary"
          size="large"
          style="width: 100%; margin-top: 20px"
          :disabled="submitDisabled"
          :loading="submitLoading"
          @click="submitLogin"
        >
          绑定
        </a-button>
        <a-button
          size="large"
          style="width: 100%; margin-top: 20px"
          @click="notBind"
        >
           暂不绑定 
        </a-button>
      </div>
    </div>
    <!-- 腾讯验证码弹层 -->
    <div id="captchaModal" v-show="showCaptcha">
      <iframe
        :src="captchaUrl"
        style="width: 100%; height: 100%"
        frameborder="no"
        border="0"
        marginwidth="0"
        marginheight="0"
        scrolling="no"
        allowtransparency="yes"
      ></iframe>
    </div>
    <!-- 图形验证码弹层 -->
    <div class="imageVerify-modal-wrap" v-if="showImageVerify">
      <div class="imageVerify-modal">
        <CloseOutlined
          class="imageVerify-modal-close"
          @click="showImageVerify = false"
        />
        <div class="flex align-center imageVerify-input-wrap">
          <div style="padding-right: 10px">图形验证码</div>
          <a-input
            placeholder="请输入图形验证码"
            size="large"
            v-model:value="imageVerifyCode"
            :max-length="4"
            autofocus
            ref="imageVerifyInputRef"
            class="imageVerify-input"
          />
          <img
            :src="imageVerifyImg"
            alt=""
            class="imageVerify-img"
            @click="getVerifyImage"
          />
          <SyncOutlined
            class="imageVerify-img-refresh"
            @click="getVerifyImage"
          />
        </div>
        <a-button
          class="imageVerify-btn"
          type="primary"
          size="large"
          @click="getSmsCode()"
          :disabled="!imageVerifyCode || imageVerifyCode.length < 4"
        >
          确定
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  ref,
  nextTick,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import { CloseOutlined, SyncOutlined } from "@ant-design/icons-vue";
let qrCodeTimer = null;
export default defineComponent({
  name: "LoginModal",
  components: { CloseOutlined, SyncOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },

  setup(props, context) {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      loginQrCodeUrl: "",
      loginMode: null, //登录模式：code:手机验证码；scan:扫码

      phoneNumber: "", //手机号
      verifyCode: "", //验证码
      phoneChecked: false, //获取手机验证码按钮可点击状态
      readCheck: true, // 是否勾选用户协议和隐私政策
      timeCount: 60, // 重新获取验证码倒计时
      timeCounting: false, // 验证码是否在倒计时

      showCaptcha: false, // 是否展示腾讯码弹层
      captchaInfo: {}, // 腾讯验证码信息
      captchaUrl: "", // 腾讯验证码iframe地址

      submitDisabled: true,
      submitLoading: false,
      user_agreement_url: "", //用户协议url

      showImageVerify: false, // 是否展示图形码弹层
      imageVerifyToken: "", // 图形验证码-token
      imageVerifyCode: null, // 图形验证码-图片
      imageVerifyImg: "", // 图形验证码-输入

      showSwitchTypeButton: false,
    });

    const phoneInputRef = ref(null);

    const onClose = () => {
      context.emit("onClose");
    };

    const getQrCode = () => {
      let BASE_URL = location.origin;
      if (process.env.NODE_ENV === "development") {
        BASE_URL = "https://chatgpt.kuaijingai.com";
      }
      let params = {
        link: BASE_URL + "/h5/pages/chatAi/login?org_id=" + utils.getOrgId(),
        hideErrMsg: true,
      };
      let source = localStorage.getItem("USER_ACCESS_SOURCE");
      let sourceInfo = localStorage.getItem("USER_ACCESS_SOURCE_INFO");

      if (source) {
        params.link =
          BASE_URL +
          "/h5/pages/chatAi/login?org_id=" +
          utils.getOrgId() +
          "&source=" +
          source;
      }
      request
        .get("/third", "/wechat/loginCode", { ...params })
        .then((res) => {
          state.loginQrCodeUrl = res.url;
          state.loginMode = "scan";
          qrCodeTimer = setInterval(() => {
            // 检查登录
            request
              .get("/third", "/pc/checkLogin", { scene_id: res.scene_id })
              .then((result) => {
                if (typeof result == "object" && result.third_token) {
                  // 登录成功
                  clearInterval(qrCodeTimer);
                  qrCodeTimer = null;

                  request
                    .post("/user", "/login/afterThird", {
                      third_token: result.third_token,
                    })
                    .then((loginResult) => {
                      utils.setUserToken(loginResult.token).then(() => {
                        console.log(utils.getUserToken());
                        //获取智媒通的登录身份
                        let params = {
                          third_id: result.third_id,
                        };
                        let code = localStorage.getItem("INVITE_CODE");
                        if (code) {
                          params.code = code;
                          localStorage.removeItem("INVITE_CODE");
                        }
                        if (source) {
                          params.source = source;
                        }
                        if (sourceInfo) {
                          params.source_info = JSON.parse(sourceInfo);
                        }
                        request
                          .post("/work_ai", "/user/info", {
                            ...params,
                          })
                          .then((userResult) => {
                            store.commit(
                              "SET_TOKEN",
                              userResult.user.user_token
                            );
                            store.commit("SET_USER_INFO", userResult.user);

                            context.emit("loginCallback");
                          });
                      });
                    });
                }
              });
          }, 2000);
        })
        .catch((err) => {
          // 获取扫码错误时自动切换到验证码登录
          state.loginMode = "code";
          // 手机号码input自动聚焦
          nextTick(() => {
            if (phoneInputRef.value) {
              phoneInputRef.value.focus();
            }
          });
        });
    };

    const changeLoginMode = (mode) => {
      state.loginMode = mode;
      if (mode == "code") {
        clearInterval(qrCodeTimer);
        qrCodeTimer = null;
        // 手机号码input自动聚焦
        nextTick(() => {
          if (phoneInputRef.value) {
            phoneInputRef.value.focus();
          }
        });
        state.showSwitchTypeButton = true;
      } else {
        getQrCode();
      }
    };

    const phoneFormat = (val, preVal) => {
      if (val && val.length > 11) {
        state.phoneNumber = preVal;
        return;
      }
      const reg = /^[0-9]*$/;
      if (reg.test(val)) {
        state.phoneNumber = val;
      } else {
        state.phoneNumber = preVal;
      }
    };

    /**************************************
     * @description: 手机号验证
     **************************************/
    // 监听电话号码输入
    watch(
      () => state.phoneNumber,
      (phone, prePhone) => {
        phoneFormat(phone, prePhone);
        if (phone.length == 11) {
          // 验证电话号码是否填写正确
          if (utils.phoneReg.test(phone)) {
            state.phoneChecked = true;
          } else {
            message.error("请输入正确的手机号码！");
          }
        } else if (phone.length < 11 && !state.phoneChecked) {
          state.phoneChecked = false;
        }
      }
    );

    /**************************************
     * @description: 获取验证码
     **************************************/
    const getCode = () => {
      if (!state.readCheck) {
        message.warning("请确认已阅读并同意《服务协议》！");
        return;
      }
      store.dispatch("GetConfigInfo").then((config) => {
        if (config && config.captcha) {
          const { captcha_type, captcha_qcloud_appid } = config.captcha;
          if (captcha_type == 1) {
            // 显示腾讯验证码
            let baseUrl =
              process.env.NODE_ENV == "production"
                ? location.origin
                : "http://127.0.0.1";
            state.captchaUrl = `${baseUrl}/public_web/qcloudCaptcha.html?qcloudAppid=${captcha_qcloud_appid}&t=${Math.random()}`;
            console.log(" state.captchaUrl", state.captchaUrl);
            state.captchaInfo = {};
            state.showCaptcha = true;
          } else if (captcha_type == 2) {
            // 图形验证码
            getVerifyImage();
          } else {
            // 无需验证则进入短信验证码
            getSmsCode();
          }
        } else {
          // 无需验证则进入短信验证码
          getSmsCode();
        }
      });
    };

    let codeTimer = null;
    const getSmsCode = () => {
      const params = {
        phoneCountry: "86",
        phone: state.phoneNumber,
        smsType: "sms_code",
        remark: `org_user_${state.currentLoginType}_login`,
        sms_code_length: 4,
      };
      store.dispatch("GetConfigInfo").then((config) => {
        console.log(config);
        if (config && config.captcha) {
          const { captcha_type } = config.captcha;
          if (captcha_type == 1) {
            params.captchaTicket = state.captchaInfo.ticket;
            params.captchaRandstr = state.captchaInfo.randstr;
          }
          if (captcha_type == 2) {
            params.captchaToken = state.imageVerifyToken;
            params.captchaInput = state.imageVerifyCode;
          }
          if (config.basic && config.basic.oem_org_id) {
            params.org_id = config.basic.oem_org_id;
          }
          request
            .post("/message", "/sms/sendSmsCodeGuest", params)
            .then(() => {
              message.success("验证码已发送");
              if (captcha_type == 2) {
                state.showImageVerify = false;
                state.imageVerifyCode = null;
                state.imageVerifyImg = "";
                state.imageVerifyToken = "";
              }
              codeTimer && clearTimer();
              codeTimer = setInterval(() => {
                state.timeCounting = true;
                if (state.timeCount == 0) {
                  clearTimer();
                  state.timeCounting = false;
                }
                state.timeCount--;
              }, 1000);
            })
            .catch((err) => {
              message.error(err.msg);
              state.imageVerifyCode = null;
              getVerifyImage();
            });
        }
      });
    };

    const clearTimer = () => {
      if (codeTimer) {
        state.timeCounting = false;
        clearInterval(codeTimer);
        codeTimer = null;
      }
    };

    const getAiConfig = () => {
      request.get("/work_ai", "/config").then((res) => {
        if (res.list) {
          state.user_agreement_url = res.list.user_agreement_url;
        }
      });
    };

    const init = () => {
      getQrCode();
      getAiConfig();
      //  监听腾讯验证码message
      window.addEventListener(
        "message",
        (e) => {
          if (e.data) {
            const { type } = e.data;
            if (type === "qcloudCaptchaResult") {
              state.showCaptcha = false;
              const { res } = e.data;
              if (res && res.ticket && res.randstr) {
                state.captchaInfo = res;
                getSmsCode();
              }
            }
          }
        },
        false
      );

      // 手机号码input自动聚焦
      nextTick(() => {
        if (phoneInputRef.value) {
          phoneInputRef.value.focus();
        }
      });
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          clearInterval(qrCodeTimer);
          qrCodeTimer = null;
          state.showImageVerify = false;
          state.imageVerifyCode = null;
          state.imageVerifyImg = "";
          state.imageVerifyToken = "";
        }
      }
    );

    // 监听验证码输入
    watch(
      () => state.verifyCode,
      (code) => {
        if (code.length == 4) {
          state.submitDisabled = false;
        } else {
          state.submitDisabled = true;
        }
      }
    );

    const submitLogin = () => {
      state.submitLoading = true;
      let params = {
        phone_country: "86",
        phone: state.phoneNumber,
        code: state.verifyCode,
      };

      request
        .put("/work_ai", "/user/alterPhone", params)
        .then((res) => {
          store.commit("SET_USER_INFO", null);
          message.success("绑定成功");
          context.emit("loginCallback");
          state.submitLoading = false;
        })
        .catch(() => {
          state.submitLoading = false;
        })
        .finally(() => {
          state.submitLoading = false;
        });
    };

    const notBind = () => {
      context.emit("loginCallback");
    };

    // 用户协议
    const toUserAgreement = () => {
      window.open(state.user_agreement_url, "_blank");
    };

    const imageVerifyInputRef = ref(null);

    const getVerifyImage = () => {
      request.get("/message", "/verify/image", {}).then((res) => {
        if (res.token && res.image) {
          state.imageVerifyToken = res.token;
          state.imageVerifyImg = res.image;
          state.showImageVerify = true;
          nextTick(() => {
            if (imageVerifyInputRef.value) {
              imageVerifyInputRef.value.focus();
            }
          });
        }
      });
    };

    return {
      ...toRefs(state),
      onClose,
      changeLoginMode,
      getCode,
      submitLogin,
      toUserAgreement,
      phoneInputRef,
      getVerifyImage,
      imageVerifyInputRef,
      getSmsCode,
      notBind,
    };
  },
});
</script>

<style lang="less" scoped>
.modal-content {
  padding: 50px;
  position: relative;

  .header-title {
    font-size: 24px;
    font-weight: 500;
  }

  .header-sub-title {
    margin-top: 5px;
    color: #999;
  }

  .scan-header {
    width: 100%;
  }

  .login-qrcode {
    width: 180px;
    height: 180px;
    margin: 67px auto;
    display: block;
  }

  .switch-type {
    position: absolute;
    top: 0;
    right: 0;
    width: 80px;
    height: 80px;
    cursor: pointer;

    .switch-type-img {
      width: 80px;
      height: 80px;
      object-fit: cover;
    }

    .switch-type-tip {
      background-color: @primary-color;
      color: #fff;
      border-radius: 4px;
      width: 150px;
      height: 32px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: -45px;
      right: 0;

      &::after {
        content: "";
        position: absolute;
        bottom: -4px;
        right: 15px;
        transform: translateX(-50%) rotate(45deg);
        border: 1px solid @primary-color;
        background: @primary-color;
        width: 7.8px;
        height: 7.8px;
        border-left: 0;
        border-bottom: 0;
      }
    }
  }

  .phone-input-wrap {
    padding-bottom: 5px;
  }

  .code-input-wrap {
    margin-top: 30px;
    margin-bottom: 15px;
    padding-bottom: 5px;
    border-bottom: 1px solid #f1f1f1;

    &:hover {
      border-bottom: 1px solid @primary-color;
    }
  }

  :deep(.phone-input) {
    flex: 1;
    border: none;
    box-shadow: none;
    border-bottom: 1px solid #f1f1f1;

    &:focus {
      border-bottom: 1px solid @primary-color;
    }
  }

  :deep(.code-input) {
    flex: 1;
    border: none;
    box-shadow: none;
  }
}
#captchaModal {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
  width: 100%;
  height: 100%;
}

.imageVerify-modal-wrap {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);

  .imageVerify-modal {
    width: 444px;
    height: 230px;
    background-color: #fff;
    border-radius: 4px;
    padding: 60px 30px 30px 30px;
    position: relative;

    .imageVerify-modal-close {
      position: absolute;
      top: 0;
      right: 0;
      cursor: pointer;
      font-size: 18px;
      padding: 15px;
    }

    .imageVerify-input-wrap {
      border-bottom: 1px solid #f1f1f1;
      padding-bottom: 10px;

      :deep(.imageVerify-input) {
        flex: 1;
        border: none;
        box-shadow: none;
        border-radius: 0;
      }

      .imageVerify-img {
        width: 117px;
        height: 36px;
        margin-left: 10px;
        border: 2px solid #f1f1f1;
      }

      .imageVerify-img-refresh {
        padding: 0 6px;
        margin-left: 5px;
        font-size: 16px;
        cursor: pointer;
      }
    }

    .imageVerify-btn {
      margin-top: 40px;
      width: 100%;
    }
  }
}
</style>
